package com.zenitera.bigdata.state;

import com.zenitera.bigdata.bean.WaterSensor;
import com.zenitera.bigdata.util.BigdataUtil;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.Comparator;
import java.util.List;

/**
 * ListState<T>
 *
 */
public class Flink02_State_Key_ListState {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);

        env
                .socketTextStream("localhost", 6666)
                .map(line -> {
                    String[] data = line.split(",");
                    return new WaterSensor(
                            String.valueOf(data[0]),
                            Long.valueOf(data[1]),
                            Integer.valueOf(data[2])
                    );
                })
                .keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {


                    private ListState<Integer> top3VcState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        top3VcState = getRuntimeContext().getListState(new ListStateDescriptor<Integer>("top3", Integer.class));
                    }

                    @Override
                    public void processElement(WaterSensor value,
                                               Context ctx,
                                               Collector<String> out) throws Exception {

                        top3VcState.add(value.getVc());

                        Iterable<Integer> it = top3VcState.get();
                        List<Integer> list = BigdataUtil.toList(it);

                        list.sort(Comparator.reverseOrder());

                        if (list.size() == 4) {
                            list.remove(list.size() - 1);
                        }

                        top3VcState.update(list);

                        out.collect(list.toString());
                    }
                })
                .print();


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

/*
D:\netcat-win32-1.12>nc64.exe -lp 6666
s1,1,10
s1,1,8
s1,1,12
s1,1,6
s1,1,66
s1,1,666
s1,1,6666
s1,1,88
--------------------
[10]
[10, 8]
[12, 10, 8]
[12, 10, 8]
[66, 12, 10]
[666, 66, 12]
[6666, 666, 66]
[6666, 666, 88]
 */